<?php

namespace app\admin\controller\group_activity\publish_task;

use app\admin\service\UserService;
use app\BaseController;
use app\model\ConfigModel;
use app\model\group_activity\GroupActivityTaskDepartmentModel;
use app\model\group_activity\GroupActivityTaskModel;
use app\model\group_activity\GroupActivityTaskRatingScaleModel;
use app\model\group_activity\GroupActivityTypeModel;
use app\model\MessageModel;
use app\model\RatingScaleModel;
use app\model\UserModel;
use app\socket\Server;
use think\App;
use think\swoole\Websocket;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 发布活动
     * @param Websocket $websocket
     * @return bool|string
     */
    public function index(Websocket $websocket): bool|string
    {
        $GroupActivityTaskModel = new GroupActivityTaskModel();
        $GroupActivityTaskModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'name|任务名称' => 'require',
                'cover|封面图' => 'require',
                'type_id|类型' => 'require',
                'address|地址' => 'require',
                'is_task|开始开启前置测评任务' => 'require',
                'result_read_auth|查看权限' => 'require',
                'department_id|部门' => 'require',
                'enroll_start_time|报名开始时间' => 'require',
                'enroll_end_time|报名结束时间' => 'require',
//                'enroll_matters|报名注意事项' => 'require',
                'enroll_review|是否启用报名审核' => 'require',
                'is_sign|是否需要签到' => 'require',
//                'sign_matters|签到注意事项' => 'require',
                'start_time|活动开始时间' => 'require',
                'end_time|活动结束时间' => 'require',
//                'scheme_matters|方案注意事项' => 'require',
            ]);
            if (!$param['enroll_start_time']) {
                throw new \Exception('报名开始时间不能为空！');
            }
            if (!$param['enroll_end_time']) {
                throw new \Exception('报名结束时间不能为空！');
            }
            if (!$param['start_time']) {
                throw new \Exception('活动开始时间不能为空！');
            }
            if (!$param['end_time']) {
                throw new \Exception('活动结束时间不能为空！');
            }
            if ($param['is_sign'] == 1){
                $this->validate($param,[
                    'sign_start_time|签到开始时间' => 'require',
                    'sign_end_time|签到结束时间' => 'require',
                ]);
                if (!$param['sign_start_time']) {
                    throw new \Exception('签到开始时间不能为空！');
                }
                if (!$param['sign_end_time']) {
                    throw new \Exception('签到结束时间不能为空！');
                }
            }
            if ($param['is_task'] == 1){
                $this->validate($param,[
                    'rating_scale_id|前置测评任务' => 'require',
                ]);
            }
            $param['unit_id'] = $this->userData['unit_id'];
            $param['uid'] = $this->userData['id'];
            $param['time'] = time();
            if ($param['enroll_start_time'] >= $param['time'] && $param['enroll_end_time'] <= $param['time']) {
                $param['status'] = 2;
            }
            //活动部门
            if (!empty($param['department_id'])) {
                $departmentData = [];
                foreach ($param['department_id'] as $department_id) {
                    $departmentData[] = [
                        'department_id' => $department_id,
                        'time' => time()
                    ];
                }
                unset($param['department_id']);
            }
            //活动测评量表
            if (!empty($param['rating_scale_id'])) {
                $ratingScaleData = [];
                foreach ($param['rating_scale_id'] as $rating_scale_id) {
                    $ratingScaleData[] = [
                        'rating_scale_id' => $rating_scale_id,
                        'time' => time()
                    ];
                }
                unset($param['rating_scale_id']);
            }
            $task_id = $GroupActivityTaskModel->insertGetId($param);
            //活动部门
            if (!empty($departmentData)) {
                foreach ($departmentData as &$department) {
                    $department['task_id'] = $task_id;
                }
                $GroupActivityTaskDepartmentModel = new GroupActivityTaskDepartmentModel();
                $GroupActivityTaskDepartmentModel->insertAll($departmentData);
            }
            //活动测评量表
            if (!empty($ratingScaleData)) {
                foreach ($ratingScaleData as &$ratingScale) {
                    $ratingScale['task_id'] = $task_id;
                }
                $GroupActivityTaskRatingScaleModel = new GroupActivityTaskRatingScaleModel();
                $GroupActivityTaskRatingScaleModel->insertAll($ratingScaleData);
            }
            $ConfigModel = new ConfigModel();
            $config = $ConfigModel->where([
                ['unit_id','=', $this->userData['unit_id']],
                ['key','=','group_activity']
            ])->value('value')??'';
            $config = json_decode($config,true);
            $socketServer = new Server();
            if (!empty($config['is_send_message'])) {
                $UserModel = new UserModel();
                $MessageModel = new MessageModel();
                $uid = $UserModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['role_mode','=',3]
                ])->column('id');
                //推送socket消息
                $fd = $socketServer->uidGetFd($uid);
                $MessageData = [];
                foreach ($config['send_message'] as $value) {
                    foreach ($uid as $v) {
                        $MessageData[] = [
                            'uid' => $v,
                            'channel' => $value,//接收渠道
                            'type' => 23,
                            'title' => '系统推送',
                            'content' => '管理员发布了新的活动',
                            'time' => time()
                        ];
                    }
                    $socketData[] = [
                        'type' => 'message',
                        'content' => [
                            'type' => 23,
                            'channel' => $value,//接收渠道
                            'title' => '系统推送',
                            'content' => '管理员发布了新的活动',
                            'img' => match (23){
                                3,4,5,7,8,9,10 => '/icon_task/202411/07_1730960087672c5ad715646.png',//测评任务消息
                                6,11, 1, 2, 14, 15, 16,23 => '/icon_task/202411/07_1730960430672c5c2ee2c98.png',//预警报告消息-系统通知-公告-危机干预
                                17 => '/icon_task/202411/07_1730944047672c1c2fd624c.png',//预约咨询消息
                                22 => '/icon_task/202411/07_1730941588672c1294c2e1e.png',//物联网消息
                            },
                            'time' => time()
                        ]
                    ];
                }
                if (!empty($MessageData)){
                    $MessageModel->insertAll($MessageData,500);
                }
            }
            $GroupActivityTaskModel->commit();
            if (!empty($socketData) && !empty($fd)){
                foreach ($socketData as $v){
                    //推送socket消息
                    $socketServer->push($fd,json_encode($v),$websocket);
                }
            }
            return success();
        } catch (\Exception $e) {
            $GroupActivityTaskModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 类型选择器
     * @return bool|string
     */
    public function typeSelector(): bool|string
    {
        try {
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $where[] = ['status', '=', 1];
            $GroupActivityTypeModel = new GroupActivityTypeModel();
            $data = $GroupActivityTypeModel->field('id,name')
                ->where($where)->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 获取部门名称
     * @return bool|string
     */
    public function getDepartmentName(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $nameData = [];
            $UserService = new UserService($this->app);
            $DepartmentData = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
            foreach ($param['id'] as $department_id) {
                if ($department_id > 0){
                    $nameData[] = $DepartmentData[$department_id]['all_name']??'--';
                }
            }
            return success(implode('、', $nameData));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 获取量表内容
     * @return bool|string
     */
    public function getRatingScale(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $RatingScaleModel = new RatingScaleModel();
            $data = $RatingScaleModel->field('id,name,cover')->where('id','in',$param['id'])->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }
}